#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调整挂机参数使其与角色属性精确对应
修复收益计算中的问题并优化挂机系统
"""

import sqlite3
import json
from database.database_manager import DatabaseManager
from src.character.experience_system import exp_system

def adjust_idle_parameters():
    """调整挂机参数与角色属性的对应关系"""
    print("=== 调整挂机参数与角色属性对应关系 ===")
    
    db_manager = DatabaseManager()
    
    try:
        # 1. 分析当前问题
        print("\n1. 当前问题分析...")
        
        problems = []
        
        # 检查挂机地点倍率是否被正确使用
        print("   检查挂机地点倍率使用情况...")
        locations_query = """
        SELECT id, name, base_exp_rate, min_level, max_level
        FROM idle_locations
        ORDER BY min_level
        """
        locations = db_manager.execute_query(locations_query)
        
        print(f"   发现问题: 挂机管理器中地点倍率未被使用")
        problems.append("地点经验倍率在收益计算中被忽略")
        
        # 检查角色属性是否影响收益
        print("   检查角色属性对收益的影响...")
        characters_query = """
        SELECT c.id, c.name, c.character_class, c.level, c.attack, c.defense, c.hp, c.mp, c.speed
        FROM characters c
        JOIN accounts a ON c.account_id = a.id
        WHERE a.username = 'test'
        """
        characters = db_manager.execute_query(characters_query)
        
        if characters:
            # 检查不同职业是否有不同的收益
            classes = set(char['character_class'] for char in characters)
            if len(classes) > 1:
                print(f"   发现多个职业: {', '.join(classes)}")
                problems.append("不同职业的收益计算没有差异化")
            
            # 检查属性是否影响收益
            attributes = ['attack', 'defense', 'hp', 'mp', 'speed']
            attr_values = {attr: set(char[attr] for char in characters) for attr in attributes}
            
            uniform_attrs = [attr for attr, values in attr_values.items() if len(values) == 1]
            if uniform_attrs:
                print(f"   发现统一属性: {', '.join(uniform_attrs)}")
                problems.append(f"角色属性 {', '.join(uniform_attrs)} 对收益没有影响")
        
        print(f"\n   发现 {len(problems)} 个问题:")
        for i, problem in enumerate(problems, 1):
            print(f"   {i}. {problem}")
        
        # 2. 提出优化方案
        print("\n2. 优化方案设计...")
        
        print("   方案1: 修复地点倍率使用")
        print("   - 修改挂机管理器，使地点经验倍率正确应用于收益计算")
        print("   - 确保不同地点有明显的收益差异")
        
        print("   方案2: 角色属性影响收益")
        print("   - 攻击力影响经验获取速度")
        print("   - 防御力影响挂机安全性（减少意外中断）")
        print("   - 速度影响收益结算频率")
        print("   - 不同职业有不同的收益加成")
        
        print("   方案3: 平衡性调整")
        print("   - 调整地点等级要求，避免等级空档")
        print("   - 优化经验倍率分布，确保合理的收益梯度")
        
        # 3. 实施优化
        print("\n3. 实施优化方案...")
        
        # 3.1 更新地点配置
        print("   3.1 优化挂机地点配置...")
        
        # 重新设计地点的经验倍率，确保有明显差异
        location_updates = [
            (1, 1.0, "适合新手的安全区域，经验倍率标准"),
            (2, 1.3, "森林外围，怪物较弱，经验倍率略高"),
            (3, 1.8, "深林区域，危险但收益丰厚"),
            (4, 1.5, "山洞入口，平衡的风险与收益"),
            (5, 2.5, "古老遗迹，神秘力量加成经验获取"),
            (6, 3.5, "龙穴深处，极高风险极高收益")
        ]
        
        for loc_id, new_rate, description in location_updates:
            update_query = """
            UPDATE idle_locations 
            SET base_exp_rate = %s, description = %s
            WHERE id = %s
            """
            db_manager.execute_update(update_query, (str(new_rate), description, loc_id))
            print(f"   - 更新地点 {loc_id}: 经验倍率 {new_rate}")
        
        # 3.2 创建角色属性加成配置
        print("   3.2 设计角色属性加成系统...")
        
        # 职业加成配置
        class_bonuses = {
            '战士': {'exp_bonus': 1.1, 'description': '战斗经验丰富，经验获取+10%'},
            '法师': {'exp_bonus': 1.2, 'description': '学习能力强，经验获取+20%'},
            '刺客': {'exp_bonus': 1.05, 'description': '敏捷灵活，经验获取+5%'},
            '牧师': {'exp_bonus': 1.15, 'description': '智慧加成，经验获取+15%'}
        }
        
        # 保存配置到数据库
        config_query = """
        INSERT INTO game_config (config_key, config_value, description) 
        VALUES (%s, %s, %s)
        ON DUPLICATE KEY UPDATE 
        config_value = VALUES(config_value), 
        description = VALUES(description)
        """
        
        # 检查是否存在game_config表
        try:
            db_manager.execute_query("SELECT 1 FROM game_config LIMIT 1")
            config_table_exists = True
        except:
            config_table_exists = False
            print("   - game_config表不存在，跳过配置保存")
        
        if config_table_exists:
            for class_name, bonus_info in class_bonuses.items():
                config_key = f"class_exp_bonus_{class_name}"
                config_value = json.dumps(bonus_info)
                db_manager.execute_update(config_query, (config_key, config_value, f"{class_name}职业经验加成配置"))
                print(f"   - 保存 {class_name} 职业配置: {bonus_info['description']}")
        
        # 3.3 测试新的收益计算
        print("   3.3 测试新的收益计算公式...")
        
        for char in characters:
            char_level = char['level']
            char_class = char['character_class']
            char_attack = char['attack']
            
            # 测试不同地点的收益
            print(f"   角色: {char['name']} ({char_class} Lv.{char_level})")
            
            for location in locations[:3]:  # 测试前3个地点
                loc_name = location['name']
                base_exp_rate = float(location['base_exp_rate'])
                
                # 使用经验系统计算基础收益
                base_hourly_exp = exp_system.calculate_idle_exp_rate(char_level, 1.0)
                
                # 应用地点倍率
                location_exp = base_hourly_exp * base_exp_rate
                
                # 应用职业加成
                class_bonus = class_bonuses.get(char_class, {}).get('exp_bonus', 1.0)
                final_exp = location_exp * class_bonus
                
                # 应用属性加成（攻击力影响）
                attack_bonus = 1.0 + (char_attack - 10) * 0.01  # 每点攻击力超过10点增加1%
                final_exp_with_attr = final_exp * attack_bonus
                
                print(f"     {loc_name}: {base_hourly_exp:.1f} -> {location_exp:.1f} -> {final_exp:.1f} -> {final_exp_with_attr:.1f} 经验/小时")
        
        # 4. 验证优化效果
        print("\n4. 验证优化效果...")
        
        # 检查地点倍率分布
        updated_locations = db_manager.execute_query(locations_query)
        rates = [float(loc['base_exp_rate']) for loc in updated_locations]
        
        print(f"   地点经验倍率范围: {min(rates):.1f} - {max(rates):.1f}")
        print(f"   倍率差异: {max(rates) / min(rates):.1f}x")
        
        if max(rates) / min(rates) >= 2.0:
            print("   ✅ 地点间有明显收益差异")
        else:
            print("   ⚠️  地点间收益差异较小")
        
        # 检查等级覆盖
        level_ranges = [(loc['min_level'], loc['max_level'] or 999) for loc in updated_locations]
        level_ranges.sort()
        
        gaps = []
        for i in range(len(level_ranges) - 1):
            current_max = level_ranges[i][1]
            next_min = level_ranges[i + 1][0]
            if next_min > current_max + 1:
                gaps.append((current_max + 1, next_min - 1))
        
        if gaps:
            print(f"   ⚠️  发现等级空档: {gaps}")
        else:
            print("   ✅ 等级覆盖完整")
        
        # 5. 生成优化建议
        print("\n5. 进一步优化建议...")
        
        suggestions = [
            "修改挂机管理器代码，确保地点倍率被正确应用",
            "实现角色属性对收益的影响计算",
            "添加职业特色的挂机加成",
            "考虑添加装备对挂机收益的影响",
            "实现挂机地点的动态解锁机制"
        ]
        
        for i, suggestion in enumerate(suggestions, 1):
            print(f"   {i}. {suggestion}")
        
        print("\n=== 参数调整完成 ===")
        print("\n注意: 需要修改挂机管理器代码以应用这些配置更改")
        
    except Exception as e:
        print(f"❌ 调整过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # DatabaseManager使用连接池，不需要手动关闭
        pass

if __name__ == "__main__":
    adjust_idle_parameters()